<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <el-alert
          title="注意只能选择三级菜单"
          type="warning"
          :closable="false"
          show-icon>
      </el-alert>
      <!--选择商品分类区域-->
      <el-row class="goodsrow">
        <el-col>
          <span>选择商品分类:</span>
        </el-col>
      </el-row>
      <!--层叠选择框-->
      <el-cascader
          :options="cateList"
          :props="cateProps"
          @change="handleChange"
          v-model="selectedCateKeys">
      </el-cascader>
      <!--tab页签区-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--注意，tab页签，activeName双向绑定到数据里面，同时在点击的时候，也会调用tab-click的函数，一般使用的时候，会在绑定的函数中，打印双向绑定的变量，并且打印出的值是选中标签的name-->
        <!--添加动态参数-->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini"
                     :disabled="isBtnDisable" @click="showTitleVisible = true">添加属性
          </el-button>
          <!--动态参数渲染表格-->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    placeholder="请输入内容"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--序列号列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="参数名称操作">
              <!--作用域插槽-->
              <template v-slot="scope">
                <el-button type="primary" size="mini"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)"
                >编辑
                </el-button>
                <el-button type="danger" size="mini"
                           icon="el-icon-delete"
                           @click="removeId(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="showTitleVisible = true"
          >添加参数
          </el-button>
          <!--静态属性渲染表格-->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template v-slot="scope">
                <!--循环渲染tag标签-->
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
                <!--通过v-if渲染动态添加的组件-->
                <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    placeholder="请输入内容"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--序列号列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="参数名称操作">
              <!--作用域插槽-->
              <template v-slot="scope">
                <el-button type="primary" size="mini"
                           icon="el-icon-edit"
                           @click="showEditDialog(scope.row.attr_id)"

                >编辑
                </el-button>
                <el-button type="danger" size="mini"
                           @click="removeId(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--增加的弹出对话框-->
    <el-dialog
        :title="'请填写'+showTitle"
        :visible.sync="showTitleVisible"
        width="50%"
        @close="addDialogClose"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="showTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="showTitleVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
    </el-dialog>
    <!--编辑的弹出对话框-->
    <el-dialog
        :title="'请修改'+showTitle"
        :visible.sync="editTitleVisible"
        width="50%"
        @close="editDialogClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="showTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editTitleVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        cateList: [],
        cateProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          checkStrictly: false,

        },
        // 级联选择框双向绑定的数组
        selectedCateKeys: [],
        activeName: 'many',
        manyTableData: [],
        onlyTableData: [],
        // 控制添加对话框的显示隐藏
        showTitleVisible: false,
        addForm: {
          attr_name: ''
        },
        editTitleVisible: false,
        // 添加表单的规则
        //     注意 规则是一个el-form的顶级对象，
        // 里面根据每个el-form-item的prop具体定义一个数组

        addFormRules: {
          attr_name: [{required: true, message: '请输入参数名称', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}]
        },
        editForm: {
          attr_name: ''
        },
        editFormRules: {attr_name: [{required: true, message: '请输入参数名称', trigger: 'blur'}]},
        attr_id: '',
      }
    },
    methods: {
      async getCateList() {
        const {data: res} = await this.$http.get('categories')
        if (res.meta.status !== 200) return this.$message.error('获取商品内容失败')
        // console.log(res);
        this.cateList = res.data
        // console.log(this.cateList);
      },
      async handleChange() {
        // 如果不是三级分类
        if (this.selectedCateKeys.length !== 3) {
          this.selectedCateKeys = []
          return
        }
        this.getParamsData()

      },
      // tab页签绑定事件的处理函数
      handleTabClick() {
        console.log(this.activeName);
        this.getParamsData()
      },
      async getParamsData() {
        // 如果是三级分类
        const {data: res} = await this.$http.get(`categories/${this.getId}/attributes`, {params: {sel: this.activeName}})
        if (res.meta.status !== 200) {
          return this.$message.error('未能获取成功')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (res.data)
        // 一定要注意el-tab-panel的带小写的，有坑
          if (this.activeName === 'many') {
            this.manyTableData = res.data
            console.log(res.data);
          } else {
            this.onlyTableData = res.data
          }
      },
      addDialogClose() {
        this.$refs.addFormRef.resetFields()
      },
      addParams() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          const {data: res} = await this.$http.post(`categories/${this.getId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 201) {
            return this.$message.error('添加参数失败')
          }
          this.$message.success('添加参数成功')
          this.showTitleVisible = false
          this.getParamsData()
        })
      },
      // 修改的对话框
      async showEditDialog(attr_id) {
        this.attr_id = attr_id
        // console.log(this.getId);
        // 查询当前参数信息
        const {data: res} = await this.$http.get(`categories/${this.getId}/attributes/${attr_id}`, {
          params: {attr_sel: this.activeName}
        })
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数信息失败！')
        }
        this.editForm = res.data
        // 提前请求数据，最后显示对话框
        this.editTitleVisible = true
      },
      // 重置修改的表单
      editDialogClose() {
        this.$refs.editFormRef.resetFields()
      },
      editParams() {
        // console.log('ref',this.$refs);
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          const {data: res} = await this.$http.put(`categories/${this.getId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200) {
            return this.$message.error('修改参数失败')
          }
          this.$message.success('修改参数成功')
          this.editTitleVisible = false


        })
      },
      // 删除对应行的信息
      removeId(attr_id) {
        this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          const {data: res} = await this.$http.delete(`categories/${this.getId}/attributes/${attr_id}`)
          this.getParamsData()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      async handleInputConfirm(row) {
        this.saveAttrVals(row)
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrVals(row)

      },
      // 点击按钮，显示文本输入框
      showInput(row) {
        row.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      async saveAttrVals(row) {
        const {data: res} = await this.$http.put(`categoroes/${this.getId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status !== 200) {
          return this.$message.success('修改参数成功！')
        }
        this.$message.success('修改参数成功')

      },
      handleClose(i, row) {
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
      }
    },
    created() {
      this.getCateList()
    },
    computed: {
      // 如果按钮需要被禁用 返回true
      isBtnDisable() {
        if (this.selectedCateKeys.length !== 3) return true
        return false
      },
      // 获取三级分类的ID
      getId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2]
        }
        return null
      },
      // 动态给对话框的title一个名字
      showTitle() {
        if (this.activeName === 'many') {
          return '动态参数'
        } else {
          return '静态属性'
        }
      },


    }
  }
</script>

<style scoped>
  .goodsrow {
    margin: 15px auto
  }

  .el-tag {
    margin: 10px;
  }

  .input-new-tag {
    width: 123px;
  }

</style>